// import router from './router'
// import store from '@/store'

// const whiteList = '/login' // 白名单

// router.beforeEach((to, from, next) => {
//   // 取出token(vuex)
//   const token = store.state.user.token
//   if (token) {
//     // 去登录页
//     if (to.path === '/login') {
//       next('/')
//     } else {
//       next()
//     }
//   } else {
//     if (to.path === whiteList) {
//       next()
//     } else {
//       next('/login')
//     }
//     // next() // 重点强调next一定要调用
//   }
// })
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from '@/router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  // store.commit('user/delToken')
  // console.log(hasToken, 111)
  if (hasToken) {
    if (to.path === '/login') {
      console.log(3333)
      // if is logged in, redirect to the home page
      next({ path: '/' })
      // next()
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          const {
            userId,
            roles: { menus }
          } = await store.dispatch('user/getUser')
          // console.log(menus, 9999)
          const filterRouter = asyncRoutes.filter((item) => {
            // console.log(item, 54)
            const itemName = item.children[0].name //  获取所有的动态路由中的children.name
            const flag = menus.includes(itemName) // 判断name值在不在menus中
            if (flag) {
              return item
            }
          })
          filterRouter.push(
            // 404 page must be placed at the end !!!
            { path: '*', redirect: '/404', hidden: true }
          )
          //  4、仓库中合成静态和动态
          store.commit('menu/setMenuList', filterRouter)
          router.addRoutes(filterRouter)
          await store.dispatch('user/getById', userId)
          // 解决刷新出现的白屏bug
          next({
            ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
            replace: true // 重进一次, 不保留重复历史
          })
        } catch (error) {
          console.log(123123)
          // remove token and go to login page to re-login
          await store.commit('user/delToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.includes(to.path)) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
